﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QualityStormCommon;

namespace QualityStorm {
    public partial class FrmOPCTagSelection : Form {
        private OPCBranch m_TopOPCBranch;
        private string m_SelectedTagName;

        public string SelectedTagName {
            get {
                return m_SelectedTagName;
            }
            set {
                m_SelectedTagName = value;
            }
        }

        public OPCBranch TopOPCBranch {
            get {
                return m_TopOPCBranch;
            }
            set {
                m_TopOPCBranch = value;
                BuildTree();
            }
        }

        private void BuildTree() {
            treeView1.Nodes.Clear();
            foreach (object o in m_TopOPCBranch.Children) {
                if (o is OPCBranch) {
                    TreeNode node = treeView1.Nodes.Add((o as OPCBranch).Name);
                    node.ImageIndex = 0;
                    node.Tag = o;
                    FillNode(node, (o as OPCBranch));
                } else {
                    TreeNode node = treeView1.Nodes.Add((o as OPCItem).Name);
                    node.ImageIndex = 1;
                    node.SelectedImageIndex = 1;
                    node.Tag = o;

                }
            }
        }

        private void FillNode(TreeNode parentNode, OPCBranch oPCBranch) {
            foreach (object o in oPCBranch.Children) {
                if (o is OPCBranch) {
                    TreeNode node = parentNode.Nodes.Add((o as OPCBranch).Name);
                    node.ImageIndex = 0;
                    node.Tag = o;
                    FillNode(node, (o as OPCBranch));
                } else {
                    TreeNode node = parentNode.Nodes.Add((o as OPCItem).Name);
                    node.ImageIndex = 1;
                    node.Tag = o;
                    node.SelectedImageIndex = 1;
                }
            }
            
        }

        public FrmOPCTagSelection() {
            InitializeComponent();
        }

        private void FrmOPCTagSelection_Load(object sender, EventArgs e) {

        }

        private void btnOK_Click(object sender, EventArgs e) {
            SelectedTagName = treeView1.SelectedNode.Parent.Text + "." + treeView1.SelectedNode.Text;
            DialogResult = DialogResult.OK;
            Close();
            
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
            btnOK.Enabled = (e.Node.Tag is OPCItem);
        }
    }
}
